package microsfot.java;

import java.util.Stack;

public class MinStack{
	Stack<Integer> stack=new Stack<Integer>();
	
	public MinStack push(int item){
		if(stack.isEmpty()){
			stack.push(item);
			stack.push(item);
		}else{
			int top=stack.pop();
			int diff=item-top;
			
			stack.push(diff);
			stack.push(diff<0?item:top);
		}
		return this;
	}
	
	public int min(){
		return stack.peek();
	}
	
	public boolean isEmpty(){
		return stack.size()<=1;
	}
	
	public int pop(){
		int last=stack.pop();
		int diff=stack.pop();
		
		if(diff<0){
			stack.push(last-diff);
			return last;
		}else{
			if(!stack.isEmpty()){
				stack.push(last);
				return last+diff;
			}else{
				stack.push(last);
				
				return last;
			}
		}
	}
	/**
	 * 实例栈调用
	 * 3,1,4,0
	 * @param args
	 */
	public static void main(String[] args) {
		MinStack stack=new MinStack();
		stack.push(3).push(1).push(4).push(0);
		System.out.println("3,1,4,0");
		System.out.println(stack);
		System.out.println("---------------------------------------");
		System.out.println(stack.min());
		System.out.printf("pop=%d,min=%d,stack=%s\n",stack.pop(),stack.min(),stack);
		System.out.printf("pop=%d,min=%d,stack=%s\n",stack.pop(),stack.min(),stack);
		System.out.printf("pop=%d,min=%d,stack=%s\n",stack.pop(),stack.min(),stack);
		System.out.printf("pop=%d,min=%d,stack=%s\n",stack.pop(),stack.min(),stack);
		System.out.println(stack.isEmpty());
	}
	
	public String toString(){
		return stack.toString();
	}
}
